import { addDetail, getOssSecurity } from '@/services/ant-design-pro/source';
import { InboxOutlined, PlusOutlined } from '@ant-design/icons';
import { ActionType, ModalForm } from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, UploadProps, message } from 'antd';
import Dragger from 'antd/es/upload/Dragger';
import { FC, useState } from 'react';
import OSS from 'ali-oss';
import dayjs from 'dayjs';
import { AesDecrypt } from '@/utils/aes';
import { set } from 'lodash';

interface CreateFormProps {
  reload?: ActionType['reload'],
  param?: any,
}

const CreateForm: FC<CreateFormProps> = (props) => {
  const { reload, param } = props;
  const [fileList, setFileList] = useState<any[]>([]);
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    maxCount:20,
    beforeUpload(file, fileList) {
      const isPdf  = file.type === 'application/pdf';
      if (!isPdf) {
        message.error(`请上传pdf文件`);
      }
      return isPdf;
    },
    onChange(info) {
      const {file} = info;
      const { status } = file;
      const {typeId ,booksId, id} = param;
      const date = dayjs(new Date().getTime()).format('YYYYMM');
      const fileNameArray = file.name.split('.');
      const name = encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-4);
      if(file.type == "application/pdf"){
        setFileList(info.fileList);
      }
      if (status === "removed") {
        const newFile = fileList.filter(i => i.name !== info.file.name);
        setFileList(newFile);
      }
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
  };

  const [messageApi, contextHolder] = message.useMessage();
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const { run, loading } = useRequest(addDetail, {
    manual: true,
    onSuccess: () => {
      messageApi.success('添加成功');
      reload?.();
    },
    onError: () => {
      messageApi.error('添加失败!');
    },
  });
  const uploadOss = async (e:any) =>{
    const { typeId ,booksId, id} = param;
    const {obj} = await getOssSecurity();
    const ossDt = JSON.parse(AesDecrypt(obj));
    const tempFilePath = e.file.name;
    const index = tempFilePath.lastIndexOf('.');
    const fileNameArray = tempFilePath.split('.');
    console.log(encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-4));
    const suffix = tempFilePath.substr(index + 1);
    const random = encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-4);
    const fileName = random+'.'+suffix;
    const date = dayjs(new Date().getTime()).format('YYYYMM');
    const client = new OSS({
      region: 'oss-cn-shenzhen',
      bucket: 'ky-data',
      accessKeyId: ossDt.accessKeyId,
      accessKeySecret: ossDt.accessKeySecret,
      stsToken: ossDt.securityToken,
      secure: true,
    }); 
    const {name, res, url} = await client.put(`/books/source/${typeId}/${booksId}/${id}/${date}`+fileName, e.file);
    if(res.status === 200){
      const upFile = fileList.filter(i => i.name === tempFilePath );
      const oldFile =  fileList.filter(i => i.name !== tempFilePath );
      if(upFile.length > 0){
        upFile[0].status = 'done';
      }
      const newFileList = [...oldFile, ...upFile]
      setFileList(newFileList);
    }
  }

  return (
    <>
      {contextHolder}
      <ModalForm
        title={intl.formatMessage({
          id: 'pages.searchTable.createForm.newRule',
          defaultMessage: 'New rule',
        })}
        trigger={
          <Button type="primary" icon={<PlusOutlined />}>
            <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>
        }
        width="400px"
        modalProps={{ okButtonProps: { loading },destroyOnClose: true }}
        onFinish={async (value) => {
          const { typeId ,booksId, id} = param;
          const sources = [];
          for(var i=0;i<fileList.length;i++){
            const fileId = i;
            const name = fileList[i].name;
            const tempFilePath = fileList[i].name;
            const index = tempFilePath.lastIndexOf('.');
            const fileNameArray = tempFilePath.split('.');
            console.log(encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-4));
            const suffix = tempFilePath.substr(index + 1);
            const random = encodeURIComponent(fileNameArray[0]).replaceAll('%','').slice(-4);
            const fileName = random+'.'+suffix;
            const date = dayjs(new Date().getTime()).format('YYYYMM');
            const source =   `/books/source/${typeId}/${booksId}/${id}/${date}`+fileName;
            const data = {
              'id': fileId,
              'name':fileNameArray[0],
              'cover': '',
              'source':source,
            }
            sources.push(data);
          }
          const params = { releaseId: param.id, sources: JSON.stringify(sources)}
          await run(params);
          return true;
        }}
      >
        <Dragger {...uploadProps} customRequest={uploadOss} fileList={fileList}>
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">单击或拖动文件到此区域进行上传</p>
          <p className="ant-upload-hint">支持单次或批量上传</p>
        </Dragger>
      </ModalForm>
    </>
  );
};

export default CreateForm;

